<?php
/**
 * Date: 2018/6/27
 * Time: 18:02
 * Author: zeronlee
 */

namespace App\Http\Controllers\Backend\ProjectManage;


use App\Http\Controllers\Controller;
use App\Models\Access\Role\Role;
use App\Models\Access\User\User;
use App\Models\App;
use App\Models\Flaw\Vuls;
use App\Models\ProjectManage\ProjectTask;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Facades\Excel;

class ProjectManageController extends Controller
{

    /**
     * 列表
     */
    public function index (Request $request){

        #learn route
        $group = [Role::ROLE_SUPER_ADMIN,Role::ROLE_ADMIN,Role::ROLE_AUDIT_ADMIN];
        $apps = App::whereIn('id',access()->hasApps())->get();
        $pcp  = User::select(['users.id','users.name'])->distinct()->whereIn('assigned_roles.role_id',$group)->join('assigned_roles',function ($join){
            $join->on(['assigned_roles.user_id'=>'users.id']);
        })->get();
        $pageNum = 10;

        return view('backend.projectmanage.pmindex',['apps'=>$apps,'pcp'=>$pcp,'appId'=>intval($request->app),'pageNum'=>$pageNum]);
    }

    /**
     * 查询
     */
    public function search (Request $request){
        $pt = new ProjectTask();
        if ($request->search['value']){

            $pt->initWhere($request->search['value']);
        }
        $sel = ['project_task.id','project_task.pro_number','project_task.name','project_task.pcp','project_task.status','project_task.started_at','project_task.ended_at','project_task_app.app_id'];
        $list = $pt->lists($sel,[$request->start,$request->length]);
        //总数
        $count = $pt->getCount();
        $data = array('draw'=>$request->draw,'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$list);
        return response()->json($data);
    }

    /**
     * 新建页面
     */
    public function addPage (Request $request){

        $group = [Role::ROLE_SUPER_ADMIN,Role::ROLE_ADMIN,Role::ROLE_AUDIT_ADMIN];
        $apps = App::whereIn('id',access()->hasApps())->get();
        $pcp  = User::select(['users.id','users.name'])->distinct()->whereIn('assigned_roles.role_id',$group)->join('assigned_roles',function ($join){
            $join->on(['assigned_roles.user_id'=>'users.id']);
        })->get();
        return view('backend.projectmanage.pmadd',['apps'=>$apps,'pcp'=>$pcp,'statusArr'=>ProjectTask::getStatusArr()]);
    }

    /**
     * 提交记录
     */
    public function addRow (Request $request){
        $pm = new ProjectTask();
        $validator = $pm->validate($request);
        if ($validator->fails()) {
            return redirect('admin/pmaddpage')
                ->withErrors($validator)
                ->withInput();
        }
        try{

            $pm->addRow($request);
        }catch (\Exception $e){
            \Log::info($e->getMessage());
        }
        return redirect('admin/pmindex');
    }

    /**
     * 导出
     */
    public function export (Request $request){
        $cellData = [
            ['编号','项目名称','目标应用','责任人','开始时间','结束时间','状态','严重','高危','中危','低危','应用类型']
        ];
        $fillField = array();
        //如果缓存更新了，使用最新的，否则使用旧的
        $pt = new ProjectTask();
        $where = Cache::pull('ptwhere-'.Auth::user()->id);
        if (!is_array($where))
            $where = [];
        $sel = ['project_task.id','project_task.pro_number','project_task.name','project_task.pcp','project_task.status','project_task.started_at','project_task.ended_at','project_task_app.app_id'];
        $pt->requestWhere = $where;
        $data = $pt->lists($sel,[0,$pt->getCount()]);
        // $data = Cache::pull('ptlist-'.Auth::user()->id);
        if (!$data)abort(500,'导出数据为空！');
        foreach ($data as $d){
            $fillField[] = $d->pro_number;
            $fillField[] = $d->name;
            $fillField[] = $d->app;
            $fillField[] = $d->pcp;
            $fillField[] = $d->started_at;
            $fillField[] = $d->ended_at;
            $fillField[] = ProjectTask::$status[$d->status];
            $fillField[] = $d->vul_serious_num;
            $fillField[] = $d->vul_highrisk_num;
            $fillField[] = $d->vul_inrisk_num;
            $fillField[] = $d->vul_low_num;
            $type = App::where(['id'=>intval($d['app_id'])])->value('type');
            $fillField[] = App::$type[intval($type)];
            $cellData[] = $fillField;
            $fillField = array();
        }
        $excelTitle = '项目管理-'.date('Ymds',time());
        Excel::create($excelTitle,function($excel) use ($cellData){
            $excel->sheet('task', function($sheet) use ($cellData){
                $sheet->rows($cellData);
                //mac乱码
                ob_end_clean();
            });
        })->export('xls');
    }
    /**
     * 查看详情
     */
    public function detail (Request $request){
        $pt = new ProjectTask();
        $group = [Role::ROLE_SUPER_ADMIN,Role::ROLE_ADMIN,Role::ROLE_AUDIT_ADMIN];
        $apps = App::whereIn('id',access()->hasApps())->get();
        $pcp  = User::select(['users.id','users.name'])->distinct()->whereIn('assigned_roles.role_id',$group)->join('assigned_roles',function ($join){
            $join->on(['assigned_roles.user_id'=>'users.id']);
        })->get();
        //详情信息
        $item = ProjectTask::find(intval($request->id));
        $item->app = ProjectTask::getAppById($item->id);
        $item->app->typeStr = isset($item->app->type) ?App::$type[$item->app->type] : '';
        $item->app->isforeignStr = isset($item->app->is_foreign) ? App::$is_foreign[$item->app->is_foreign] : '';
        //应用详情
        $ogzs = ProjectTask::getAppItem($item->id);
        $appItem = '';
        foreach ($ogzs as $ogz)
            $appItem .= $ogz['name'] . '->';
        $item->app->ogz = rtrim($appItem,'->');
        $item->app->userStr = ProjectTask::getAppUserInfoStr($item->app->user_id);
        //测试记录
        $data = Cache::pull('ptlist-'.Auth::user()->id);
        if (empty($data)){
            $sel = ['project_task.id','project_task.pro_number','project_task.name','project_task.pcp','project_task.status','project_task.started_at','project_task.ended_at','project_task_app.app_id'];
            $pt->initWhere('app='.$item->app->id.'&id!='.$request->id);
            $pt->lists($sel,[0,10]);
            $data = Cache::pull('ptlist-'.Auth::user()->id);
        }
        $item->history = $data;
        //责任人
        $item->pcpIds = explode(',',$item->pcp);
        return view('backend.projectmanage.pmdetail',['apps'=>$apps,'pcp'=>$pcp,'item'=>$item,'statusArr'=>ProjectTask::getStatusArr()]);
    }

    /**
     * 更新
     * @param Request $request
     */
    public function updateRow (Request $request){
        $pm = new ProjectTask();
        $validator = $pm->validate($request);
        if ($validator->fails()) {
            return redirect('admin/pmdetail?id='.$request->id)
                ->withErrors($validator)
                ->withInput();
        }
        try{

            $pm->updateRow($request);
        }catch (\Exception $e){
            \Log::info($e->getMessage());
        }
        return redirect('admin/pmindex');
    }

    /**
     * 测试记录列表
     */
    public function recordList (Request $request) {
        $pt = new ProjectTask();
        $sel = [
            'project_task.id',
            'project_task.pro_number',
            'project_task.name',
            'project_task.pcp',
            'project_task.status',
            'project_task.started_at',
            'project_task.ended_at',
            'project_task_app.app_id'
        ];
        $pt->initWhere('app='.$request->app_id.'&id!='.$request->id);
        $list = $pt->lists($sel,[$request->start,$request->length]);
        //总数
        $count = $pt->getCount();
        $data = [
            'draw' => intval($request->draw),
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'data' => $list
        ];
        return response()->json($data);
    }

    /**
     * 项目发现的漏洞
     */
    public function discoverVul (Request $request){
        $pt = new ProjectTask();
        $builder = $pt->getBuilderForVul($request->id);
        $count = $builder->count();
        $list = $builder->offset($request->start)->limit($request->length)->get();
        foreach ($list as $item){
            $item->statusStr = Vuls::$vulsStatus[$item->status][0];
        }
        $data = [
            'draw' => intval($request->draw),
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'data' => $list
        ];
        return response()->json($data);
    }

    /**
     * 项目历史漏洞
     */
    public function historyVul (Request $request){
        $pt = new ProjectTask();
        $builder = $pt->getBuilderForVul($request->id,false);
        $count = $builder->count();
        $list = $builder->offset($request->start)->limit($request->length)->get();
        foreach ($list as $item){
            $item->statusStr = Vuls::$vulsStatus[$item->status][0];
        }
        $data = [
            'draw' => intval($request->draw),
            'recordsTotal' => $count,
            'recordsFiltered' => $count,
            'data' => $list
        ];
        return response()->json($data);
    }

}